#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen
@file: json_tools.back.py
@time: 2023/8/28 9:27
@desc:
"""
# coding:utf-8
import base64
import datetime
import hashlib
import json
import os
import queue
import random
import time
import tkinter
from concurrent.futures import ThreadPoolExecutor
from tkinter import ANCHOR, END, SOLID
from tkinter.ttk import Label
from urllib.request import urlopen

import psutil
import requests
from ttkbootstrap import Style

from json_tool.baidu_api import get_access_token
from json_tool.config_json_tool import app_id, api_key, secret_key_wx, secret_key_fy
from json_tool.icon import Icon
from json_tool.utils import day_laster, get_content

request_thread = None
import threading

# import tkinter as tk
import ttkbootstrap as ttk
from ttkbootstrap.constants import *

# 创建一个队列用于线程间通信
result_queue = queue.Queue()


def handle_timestamp_formate(event):
    if time_stamp_input.get():
        need_time = time_stamp_input.get().strip()
        time_local = time.localtime(int(need_time))  # 转化成localtime
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "                   " + str(time_format), "center")
    else:
        now_time = int(time.time())
        time_local = time.localtime(now_time)  # 转化成localtime
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "                   " + str(time_format), "center")


def handle_formate_timestamp(event):
    if time_formate_input.get():
        formate_data = time_formate_input.get().strip()
        if len(formate_data) == 10:
            # 转换成时间数组
            time_array = time.strptime(formate_data, "%Y-%m-%d")
            # 转换成时间戳
            time_format = int(time.mktime(time_array))
            last_print_text.delete('1.0', END)
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "                           " + str(time_format), "center")
        elif len(formate_data) == 19:  # "2023-03-21 15:11:25"
            time_array = time.strptime(formate_data, "%Y-%m-%d %H:%M:%S")
            # 转换成时间戳
            time_format = int(time.mktime(time_array))
            last_print_text.delete('1.0', END)
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "                           " + str(time_format), "center")
        elif len(formate_data) == 16:  # "2023-04-01 14:00"
            time_array = time.strptime(formate_data, "%Y-%m-%d %H:%M")
            # 转换成时间戳
            time_format = int(time.mktime(time_array))
            last_print_text.delete('1.0', END)
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "                           " + str(time_format), "center")
    else:
        now_time = int(time.time())
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "                           " + str(now_time), "center")  # ADDED


def handle_get_last_time(event):
    if can_time_stamp_input.get():
        need_time = can_time_stamp_input.get().strip()
        time_local = time.localtime(int(need_time))  # 转化成localtime
        time_format = time.strftime("%Y-%m-%d %H:%M", time_local)
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "           " + str(time_format), "center")
    else:
        now_time = int(time.time())
        time_local = time.localtime(now_time)  # 转化成localtime
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "           " + str(time_format), "center")


def handle_to_json(event):
    if sting_input.get():
        need_time = sting_input.get().strip()
        sting_output_button.delete('1.0', END)
        try:
            to_json = json.loads(need_time)
            last_send = json.dumps(to_json, ensure_ascii=False, indent=4, separators=(',', ':'))
            sting_output_button.insert(END, last_send, "center")  # ADDED
        except Exception as e:
            sting_output_button.delete('1.0', END)
            sting_output_button.insert(END, "字符串格式有误，请确认字符串使用的是为双引号\n", "center")  # ADDED
    else:
        sting_output_button.delete('1.0', END)
        sting_output_button.insert(END, "请在左边输入需要转化的字符串\n", "center")  # ADDED


def handle_auto_translate(is_en_to_zh=False):
    if sting_input.get():
        user_input = sting_input.get().strip()
        if user_input == "":
            sting_output_button.delete('1.0', END)
            sting_output_button.insert(END, "请在左边输入需要转化的字符串\n", "center")  # ADDED
        sting_output_button.delete('1.0', END)
        try:
            if not is_en_to_zh:
                from_lang = 'en'
                to_lang = 'zh'
            else:
                from_lang = 'zh'
                to_lang = 'en'
            # 你的百度翻译API应用ID和密钥
            # 生成随机数salt
            salt = str(random.randint(32768, 65536))
            # 拼接字符串1
            sign_string = app_id + user_input + salt + secret_key_fy

            # 对字符串1做MD5加密
            sign = hashlib.md5(sign_string.encode()).hexdigest()

            # 拼接完整的请求URL
            url = f'http://api.fanyi.baidu.com/api/trans/vip/translate?q={user_input}&from={from_lang}&to={to_lang}&appid={app_id}&salt={salt}&sign={sign}'

            # 发送GET请求
            response = requests.get(url)

            translated_text = "请稍后重试"
            # 解析响应数据
            if response.status_code == 200:
                result = response.json()
                translated_text = result['trans_result'][0]['dst']
                translated_text = translated_text.replace(" ", "_")
            sting_output_button.insert(END, translated_text, "center")  # ADDED
        except Exception as e:
            sting_output_button.delete('1.0', END)
            sting_output_button.insert(END, "API异常\n", "center")  # ADDED
    else:
        sting_output_button.delete('1.0', END)
        sting_output_button.insert(END, "请在左边输入需要转化的字符串\n", "center")  # ADDED


def handle_chat_message():
    chat_message = sting_input.get().strip()
    key = api_key.strip()
    sec_key = secret_key_wx.strip()
    if key and sec_key:
        if chat_message:
            if key and sec_key:
                url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + get_access_token(
                    api_key, secret_key_wx)
                payload = json.dumps({
                    "messages": [
                        {
                            "role": "user",
                            "content": f"{chat_message}"
                        }
                    ]
                })
                headers = {
                    'Content-Type': 'application/json'
                }
                response = requests.request("POST", url, headers=headers, data=payload)
                response_message = response.json().get("result")
                sting_output_button.delete('1.0', END)
                sting_output_button.insert(END, response_message, "center")  # ADDED
                request_thread = None
        else:
            sting_output_button.delete('1.0', END)
            sting_output_button.insert(END, "请在左边输入想要查询的问题\n", "center")  # ADDED
    else:
        sting_output_button.delete('1.0', END)
        sting_output_button.insert(END, "请先配置api_key,secret_key\n", "center")  # ADDED


def start_request_baidu():
    global request_thread
    if request_thread is None or not request_thread.is_alive():
        download_thread = threading.Thread(target=handle_chat_message)
        download_thread.start()


def clean_input(event):
    sting_input.delete(0, END)


def listbox_copy(event):
    window.clipboard_clear()
    selected = last_print_text.get(ANCHOR)
    selected = selected.strip()
    window.clipboard_append(selected)


def copy_to_clipboard():
    """Copy current contents of text_entry to clipboard."""
    window.clipboard_clear()  # Optional.
    window.clipboard_append(last_print_text.get('1.0', END).rstrip().strip())


def copy_to_json_clipboard():
    """Copy current contents of text_entry to clipboard."""
    window.clipboard_clear()  # Optional.
    window.clipboard_append(sting_output_button.get('1.0', END).rstrip().strip())


def get_now_time():
    time_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')  # 获取当前的时间并转化为字符串
    week_int = datetime.datetime.now().weekday()  # 获取当前的时间并转化为字符串
    date_dict = {
        0: "星期一",
        1: "星期二",
        2: "星期三",
        3: "星期四",
        4: "星期五",
        5: "星期六",
        6: "星期日",
    }
    week_str = date_dict.get(week_int)
    now_time_label.configure(text=time_str)  # 重新设置标签文本
    dat_num_label.configure(text=week_str)  # 重新设置标签文本
    window.after(10, get_now_time)  # 每隔1s调用函数 get_now_time 自身获取时间


def get_current_weather():
    code = "310000"
    key = "c7d042524a1431fb932ff9d29e34eab6"
    # 1.获取API
    url = f"https://restapi.amap.com/v3/weather/weatherInfo?city={code}&key={key}&output=JSON&extensions=base"
    # print(url)
    res = urlopen(url)
    data = json.loads(res.read())
    province = data['lives'][0]['province']  # 省份
    city = data['lives'][0]['city']  # 城市
    weather = data['lives'][0]['weather']  # 天气情况
    temperature = data['lives'][0]['temperature']  # 温度
    winddirection = data['lives'][0]['winddirection']  # 风向
    windpower = data['lives'][0]['windpower']  # 风力 级
    humidity = data['lives'][0]['humidity']  # 空气湿度
    reporttime = data['lives'][0]['reporttime'][:16]  # 发布时间
    msg = f"北京时间:{reporttime}          城市：{province}-{city}    \r\n天气:{weather}  温度:{temperature}°C  风向:{winddirection}  风力:{windpower}级  空气湿度:{humidity}%  "
    weather_stamp_show.configure(text=msg)  # 重新设置标签文本
    window.after(1000 * 60 * 60 * 6, get_current_weather)  # 每隔1s调用函数 gettime 自身获取时间


# 定义一个函数，用于在后台线程中获取CPU和内存使用率
def get_resource_usage(queue):
    """
    Retrieves CPU and memory usage metrics and stores them in a queue.
    """
    while True:
        interval = 0.5
        cpu_percent = psutil.cpu_percent(interval=1)
        memory_percent = psutil.virtual_memory().percent
        # 获取网络IO统计信息
        net_io = psutil.net_io_counters(pernic=True)

        # 初始化上传和下载的字节数
        total_upload_before = 0
        total_download_before = 0

        # 遍历所有网络接口并累加上传和下载的字节数
        for interface in net_io:
            if "以太网" in interface or "Ethernet" in interface:
                total_upload_before += net_io[interface].bytes_sent
                total_download_before += net_io[interface].bytes_recv

        # 暂停一段时间
        time.sleep(interval)

        # 再次获取网络IO统计信息
        net_io = psutil.net_io_counters(pernic=True)

        # 初始化上传和下载的增量
        total_upload_after = 0
        total_download_after = 0

        # 遍历所有网络接口并累加上传和下载的增量
        for interface in net_io:
            if "以太网" in interface or "Ethernet" in interface:
                total_upload_after += net_io[interface].bytes_sent
                total_download_after += net_io[interface].bytes_recv

        # 计算总的上传和下载速度（单位：KB/s）
        total_upload_speed = (total_upload_after - total_upload_before) / 1024 / interval
        total_download_speed = (total_download_after - total_download_before) / 1024 / interval

        queue.put((cpu_percent, memory_percent, total_upload_speed, total_download_speed))
        time.sleep(1)


def handle_memory_cpu():
    """
    处理内存和CPU显示
    :return:
    """
    try:
        cpu_nums, memory_nums, total_upload_speed, total_download_speed = result_queue.get_nowait()
        cpu_color = "#58A2D5"
        memory_color = "#9AC733"
        up_color = "#FA9014"
        down_color = "#FA9014"
        if int(cpu_nums) > 80:
            cpu_color = "#CB1B04"
        if int(memory_nums) > 80:
            memory_color = "#CB1B04"
        if total_upload_speed >= 1024:
            total_upload_speed /= 1024
            upload_unit = "MB/s"
            up_color = "#CB1B04"
        else:
            upload_unit = "KB/s"

        if total_download_speed >= 1024:
            total_download_speed /= 1024
            download_unit = "MB/s"

            down_color = "#CB1B04"
        else:
            download_unit = "KB/s"

        show_upload_speed.configure(text=f"↑:{total_upload_speed:.2f}{upload_unit}", fg=up_color)
        show_download_speed.configure(text=f"↓:{total_download_speed:.2f}{download_unit}", fg=down_color)
        show_cpu_.configure(text=f"CPU:{cpu_nums}%", fg=cpu_color)  # 重新设置标签文本
        show_memory_label.configure(text=f"内存:{memory_nums}%", fg=memory_color)  # 重新设置标签文本

    except queue.Empty:
        pass
    window.after(1000, handle_memory_cpu)


def local_day_laster():
    send = day_laster()
    last_print_text_answer.delete('1.0', END)
    last_print_text_answer.insert(END, send, "center")  # ADDED


class NewsUpdaterThread(threading.Thread):
    def __init__(self, urls, callback):
        threading.Thread.__init__(self)
        self.urls = urls
        self.callback = callback
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"}

    def run(self):
        file_name = "today.json"
        now = datetime.datetime.now()
        # 格式化为 "yyyyMMdd" 格式
        formatted_date = now.strftime('%Y%m%d')
        # data = json.load(file).get("formatted_date")
        for url in self.urls:
            try:
                dict_data = {}
                if not os.path.exists(file_name):
                    last_send = []
                    response = requests.get(url[0], headers=self.headers)
                    html = response.text
                    return_list = get_content(html, "news", url[1])
                    last_send = last_send + return_list
                    last_send.append("---------------------------")
                    last_content = "认认真真上班，这根本就不叫赚钱，那是用劳动换取报酬。"
                    _last_content = "人活半辈子才明白，真正高级的养生，是回家好好吃饭"
                    _last_content0 = "别沮丧，生活就像心电图，一帆风顺就证明你挂了！"
                    _last_content1 = "最后，祝愿天下所有摸鱼人，都能愉快的渡过每一天!"
                    _last_content2 = "关注我，这样每天我都能见到你了"
                    _last_content3 = "我是 【捣蛋小能手】 捣蛋的捣 & 捣蛋的蛋 ! "
                    _last_content4 = "email:henry_oulen@163.com"

                    last_send.append(last_content)
                    last_send.append(_last_content)
                    last_send.append(_last_content0)
                    last_send.append(_last_content1)
                    last_send.append(_last_content2)
                    last_send.append(_last_content3)
                    last_send.append(_last_content4)
                    with open(file_name, 'w+', encoding='utf-8') as file:
                        dict_data[formatted_date] = {url[1]: last_send}
                        json.dump(dict_data, file)
                else:
                    last_send = []
                    data = {}
                    with open(file_name, 'r') as file:
                        try:
                            data = json.load(file)
                            if data.get(formatted_date):
                                if data.get(formatted_date).get(url[1]):
                                    last_send = data.get(formatted_date).get(url[1])
                        except Exception as e:
                            with open(file_name, 'w+', encoding='utf-8') as file:
                                json.dump(data, file)
                    if not last_send:
                        response = requests.get(url[0], headers=self.headers)
                        html = response.text
                        return_list = get_content(html, "news", url[1])
                        last_send = last_send + return_list
                        last_send.append("---------------------------")
                        last_content = "认认真真上班，这根本就不叫赚钱，那是用劳动换取报酬。"
                        _last_content = "人活半辈子才明白，真正高级的养生，是回家好好吃饭"
                        _last_content0 = "别沮丧，生活就像心电图，一帆风顺就证明你挂了！"
                        _last_content1 = "最后，祝愿天下所有摸鱼人，都能愉快的渡过每一天!"
                        _last_content2 = "关注我，这样每天我都能见到你了"
                        _last_content3 = "我是 【捣蛋小能手】 捣蛋的捣 & 捣蛋的蛋 ! "
                        _last_content4 = "email:henry_oulen@163.com"
                        last_send.append(last_content)
                        last_send.append(_last_content)
                        last_send.append(_last_content0)
                        last_send.append(_last_content1)
                        last_send.append(_last_content2)
                        last_send.append(_last_content3)
                        last_send.append(_last_content4)
                        with open(file_name, 'w+', encoding='utf-8') as file:
                            if not data.get(formatted_date):
                                data[formatted_date] = {}
                            data[formatted_date][url[1]] = last_send
                            json.dump(data, file)
                send = ""
                for i in last_send:
                    send += i + "\r\n"
                self.callback(send)
            except requests.RequestException as e:
                print(f"Error fetching {url}: {e}")


# 示例的界面更新函数
def update_gui(news):
    # 实现更新界面的逻辑，例如更新文本框或标签
    last_print_text_answer.delete('1.0', END)
    last_print_text_answer.insert(END, news + "\n")


def local_get_today():
    urls = [['https://tophub.today/c/news', "today"]]
    thread = NewsUpdaterThread(urls, update_gui)
    thread.start()


def local_get_hot_news():
    urls = [['https://tophub.today/c/news', "hot"]]
    thread = NewsUpdaterThread(urls, update_gui)
    thread.start()


def can_time_stamp_show():
    show_string = "<-输入日期 xxxx-xx-xx xx:xx"
    if can_time_stamp_input.get():
        try:
            need_time = can_time_stamp_input.get().strip()
            if len(need_time) > 16:
                need_time = need_time[:16]
            # 将其转换为datetime对象，需要指定时间格式
            dt_obj = datetime.datetime.strptime(need_time, '%Y-%m-%d %H:%M')
            # 将datetime对象转换为时间戳（Unix时间戳）
            new_timestamp = int(dt_obj.timestamp())
            now_timestamp = int(time.time())
            # 将时间戳转换为datetime对象
            dt1 = datetime.datetime.fromtimestamp(new_timestamp)
            dt2 = datetime.datetime.fromtimestamp(now_timestamp)
            # 计算差值
            delta = dt1 - dt2
            # 获取相差的天数、小时数、分钟数和秒数
            days = delta.days
            hours, remainder = divmod(delta.seconds, 3600)
            minutes, seconds = divmod(remainder, 60)

            show_string = f"相差 {days} 天 {hours} 小时 {minutes} 分钟 {seconds} 秒"
        except Exception as e:
            show_string = "输入有误"
    else:
        need_time = "2025-01-28 12:00"
        last_period_date = "2024/04/25"
        cycle_length = 28
        # 将其转换为datetime对象，需要指定时间格式
        dt_obj = datetime.datetime.strptime(need_time, '%Y-%m-%d %H:%M')
        # 将datetime对象转换为时间戳（Unix时间戳）
        new_timestamp = int(dt_obj.timestamp())
        now_timestamp = int(time.time())
        # 将时间戳转换为datetime对象
        dt1 = datetime.datetime.fromtimestamp(new_timestamp)
        dt2 = datetime.datetime.fromtimestamp(now_timestamp)
        # 计算差值
        delta = dt1 - dt2
        # 获取相差的天数、小时数、分钟数和秒数
        days = delta.days
        hours, remainder = divmod(delta.seconds, 3600)
        minutes, seconds = divmod(remainder, 60)

        last_period_date = datetime.datetime.strptime(last_period_date, '%Y/%m/%d')
        current_date = datetime.datetime.now()

        # 计算已经过去的周期数
        elapsed_cycles = (current_date - last_period_date).days // cycle_length

        # 计算当前周期的天数
        days_into_current_cycle = (current_date - last_period_date).days % cycle_length

        # 计算总周数和剩余天数
        total_weeks = elapsed_cycles * 4 + days_into_current_cycle // 7
        remaining_days = days_into_current_cycle % 7

        show_string = f"除夕:{days}天{hours}时{minutes}分{seconds}秒 {total_weeks}d+{remaining_days}"
    can_time_stamp_show_input.configure(text=show_string)  # 重新设置标签文本
    window.after(100, can_time_stamp_show)  # 每隔1s调用函数 get_now_time 自身获取时间


def hand_today_json():
    file_name = "today.json"
    now = datetime.datetime.now()
    # 格式化为 "yyyyMMdd" 格式
    formatted_date = now.strftime('%Y%m%d')
    # data = json.load(file).get("formatted_date")formatted_date = now.strftime('%Y%m%d')
    # data = json.load(file).get("formatted_date")
    if not os.path.exists(file_name):
        data = {}
        with open(file_name, 'w+', encoding='utf-8') as file:
            json.dump(data, file)
    else:
        with open(file_name, 'r+', encoding='utf-8') as file:
            data = json.load(file)
            # 创建一个新字典来存放结果
            filtered_data = {}
            # 遍历原始字典，只保留与今日日期相匹配的项
            for key, value in data.items():
                if key == formatted_date:
                    filtered_data[key] = value
            json.dump(filtered_data, file)


window = tkinter.Tk()

with open('tmp.ico', 'wb') as tmp:
    tmp.write(base64.b64decode(Icon().img))
window.iconbitmap('tmp.ico')
os.remove('tmp.ico')

width = window.winfo_screenwidth()
window.title('小工具 @author  >> henry.oulen@gmail.com   date:2024/07/25')

# 获取屏幕尺寸计算参数，使窗口显示再屏幕中央
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
_width = 1920
_height = 1080
window_size = f'{_width}x{_height}+{round((screen_width - width) / 2)}+{round((screen_height - _height) / 2)}'  # round去掉小数

window.wm_state("zoomed")  # 设置打开的窗口最大化
window.config(bg="#1E1F22")
dat_num_label = tkinter.Label(window, text='', fg="#a9b7c6", font="等线 20 bold", bg="#1E1F22")
dat_num_label.place(relx=0.3, rely=0.02, relwidth=0.05, relheight=0.05)

# 当前时间
# now_time_label = tkinter.Label(window, text='', fg='#a9b7c6', font="等线 20 bold", bg="#5891E6")
now_time_label = tkinter.Label(window, text='', fg='#a9b7c6', font="等线 20 bold", bg="#1E1F22")
now_time_label.place(relx=0.35, rely=0.02, relwidth=0.2, relheight=0.05)
get_now_time()

# 自定义倒计时间
can_time_stamp_input = tkinter.Entry(window, font="等线 16 bold", background="#1E1F22", foreground="#a9b7c6",
                                     borderwidth=1,
                                     highlightthickness=1, relief=SOLID, highlightbackground="#a9b7c6")
can_time_stamp_input.place(relx=0.6, rely=0.02, relwidth=0.15, relheight=0.05)
# 当前时间

# can_time_stamp_show_input = tkinter.Label(window, text='', fg='#a9b7c6', font="等线 20 bold", bg="#5891E6")
# can_time_stamp_show_input = tkinter.Label(window, text='', fg='#a9b7c6', font="等线 20 bold", bg="#5891E6",fg="#5891E6")
can_time_stamp_show_input = tkinter.Label(window, text='', font="等线 19 bold", background="#1E1F22",
                                          fg="#78A817", )
can_time_stamp_show_input.place(relx=0.75, rely=0.02, relwidth=0.2, relheight=0.05)
can_time_stamp_show()

# 天气
# weather_stamp_show = tkinter.Label(window, text='天气', font="等线 11 bold", fg="#a9b7c6", bg="#5891E6")
# weather_stamp_show = tkinter.Label(window, text='天气', font="等线 11 bold", fg="#5891E6", bg="#a9b7c6")
weather_stamp_show = tkinter.Label(window, text='天气', font="等线 13 bold", background="#1E1F22",
                                   fg="#a9b7c6", )
weather_stamp_show.place(relx=0.05, rely=0.01, relwidth=0.24, relheight=0.1)
get_current_weather()

time_stamp_show = Label(window, text='时间戳', font="等线 16 bold", background="#1E1F22", foreground="#a9b7c6")
time_stamp_show.place(relx=0.05, rely=0.1, relwidth=0.12, relheight=0.07, )
time_stamp_input = tkinter.Entry(window, font="等线 16 bold", background="#1E1F22", foreground="#a9b7c6", borderwidth=1,
                                 highlightthickness=1, highlightbackground="#a9b7c6", relief=SOLID, )
time_stamp_input.place(relx=0.05, rely=0.15, relwidth=0.12, relheight=0.05)

time_formate_show = Label(window, text='时间格式', font="等线 16 bold", background="#1E1F22", foreground="#a9b7c6")
time_formate_show.place(relx=0.17, rely=0.1, relwidth=0.12, relheight=0.07, )
time_formate_input = tkinter.Entry(window, font="等线 16 bold", justify="center", background="#1E1F22",
                                   foreground="#a9b7c6", borderwidth=1,
                                   highlightthickness=1, highlightbackground="#a9b7c6", relief=SOLID, )
time_formate_input.place(relx=0.17, rely=0.15, relwidth=0.12, relheight=0.05)

timestamp_to_formate = tkinter.Button(window, text="时间戳-->格式化", command="handle_timestamp_formate",
                                      activebackground="#0f73ef", borderwidth=1, highlightthickness=1, relief=SOLID,
                                      highlightbackground="#a9b7c6",
                                      font="等线 16 bold", background="#1E1F22", foreground="#a9b7c6")
timestamp_to_formate.bind("<Button-1>", handle_timestamp_formate)
timestamp_to_formate.place(relx=0.05, rely=0.2, relwidth=0.12, relheight=0.05)

formate_to_timestamp = tkinter.Button(window, text="时间格式-->时间戳", command="handle_formate_timestamp",
                                      activebackground="#0f73ef", borderwidth=1, highlightthickness=1, relief=SOLID,
                                      font="等线 16 bold", background="#1E1F22", foreground="#a9b7c6")
formate_to_timestamp.bind("<Button-1>", handle_formate_timestamp)
formate_to_timestamp.place(relx=0.17, rely=0.2, relwidth=0.12, relheight=0.05)

last_print_text = tkinter.Text(window, width=40, height=10, border=4, relief=SOLID, font="等线 16 bold", bg="#1E1F22",
                               fg="#99C794", borderwidth=1, highlightthickness=1, highlightbackground="#a9b7c6",
                               highlightcolor="#a9b7c6")
last_print_text.place(relx=0.05, rely=0.25, relwidth=0.24, relheight=0.1)

clp_text = tkinter.Button(window, text="复制到粘贴板",
                          command=copy_to_clipboard, activebackground="#0f73ef", font="等线 16 bold",
                          background="#1E1F22", foreground="#a9b7c6")
clp_text.place(relx=0.05, rely=0.35, relwidth=0.24, relheight=0.05)


# 优化界面
# 定义消息对话框
# last_button = tkinter.Button(window, padx=5, activebackground="#0f73ef", text="节日倒数", command=local_day_laster,
#                              font="等线 16 bold", bg="#1E1F22", fg="#a9b7c6", borderwidth=1, highlightthickness=1,
#                              relief=SOLID, )
# last_button.pack()
# last_button.place(relx=0.05, rely=0.42, relwidth=0.05, relheight=0.05)


#
# last_button = ttk.Button(window, activebackground="#0f73ef", text="节日倒数", command=local_day_laster,
#                          font="等线 16 bold", bg="#1E1F22", fg="#a9b7c6", borderwidth=1, highlightthickness=1,
#                          relief=SOLID, )
# last_button.pack(padx=5,)
# # last_button.pack()
# last_button.place(relx=0.05, rely=0.42, relwidth=0.05, relheight=0.05)


style = Style()

# 设置主题
style.theme_use('darkly')

# 定义按钮样式
style.configure('Custom.TButton',
                background='#1E1F22',
                foreground='#a9b7c6',
                font=('等线', 16, 'bold'),
                padding=(5, 5))

# 创建按钮
last_button = ttk.Button(
    master=window,
    text="节日倒数",
    command=local_day_laster,
    style='Custom.TButton',  # 使用自定义样式
    bootstyle="success",  # 可以尝试不同的bootstyle看看效果
)

# 使用place布局管理器放置按钮
last_button.place(relx=0.05, rely=0.42, relwidth=0.05, relheight=0.05)

# 优化界面结束



get_hot_news_button = tkinter.Button(window, padx=5, activebackground="#0f73ef", text="今日热榜",
                                     command=local_get_hot_news, borderwidth=1, highlightthickness=1, relief=SOLID,
                                     font="等线 16 bold", bg="#1E1F22", fg="#a9b7c6", )
get_hot_news_button.pack()
get_hot_news_button.place(relx=0.145, rely=0.42, relwidth=0.05, relheight=0.05)

get_today_button = tkinter.Button(window, padx=5, activebackground="#0f73ef", text="历史今天", command=local_get_today,
                                  font="等线 16 bold", bg="#1E1F22", fg="#a9b7c6", borderwidth=1, highlightthickness=1,
                                  relief=SOLID, )
get_today_button.pack()
get_today_button.place(relx=0.24, rely=0.42, relwidth=0.05, relheight=0.05)

last_print_text_answer = tkinter.Text(window, width=40, height=10, border=4, relief=SOLID, font="等线 13 bold",
                                      bg="#1E1F22", fg="#99C794", borderwidth=1, highlightthickness=1,
                                      highlightbackground="#a9b7c6",
                                      highlightcolor="#a9b7c6")
last_print_text_answer.place(relx=0.05, rely=0.50, relwidth=0.24, relheight=0.45)

# python日志使用
# 右边
sting_input = tkinter.Entry(window, font="等线 16 bold", bg="#1E1F22",
                            fg="#a9b7c6", borderwidth=1, highlightthickness=1, highlightbackground="#a9b7c6",
                            highlightcolor="#a9b7c6", relief=SOLID, )
sting_input.place(relx=0.3, rely=0.1, relwidth=0.2, relheight=0.05)

sting_input_button = tkinter.Button(window, text="Json格式化", activebackground="#0f73ef", font="等线 16 bold",
                                    bg="#1E1F22", fg="#a9b7c6")
sting_input_button.bind("<Button-1>", handle_to_json)
sting_input_button.place(relx=0.5, rely=0.1, relwidth=0.055, relheight=0.05)

sting_auto_trans_en_button = tkinter.Button(window, text="中-->英", activebackground="#0f73ef", font="等线 16 bold",
                                            bg="#1E1F22", fg="#a9b7c6")
# sting_auto_trans_en_button.bind("<Button-1>", handle_auto_translate)
sting_auto_trans_en_button.bind("<Button-1>", lambda event, text=True: handle_auto_translate(text))
sting_auto_trans_en_button.place(relx=0.555, rely=0.1, relwidth=0.05, relheight=0.05)
sting_auto_trans_cn_button = tkinter.Button(window, text="英-->中", activebackground="#0f73ef", font="等线 16 bold",
                                            bg="#1E1F22", fg="#a9b7c6")
# sting_auto_trans_cn_button.bind("<Button-1>", handle_auto_translate)
sting_auto_trans_cn_button.bind("<Button-1>", lambda event, text=False: handle_auto_translate(text))
sting_auto_trans_cn_button.place(relx=0.605, rely=0.1, relwidth=0.05, relheight=0.05)

# baidu_btn_button = tkinter.Button(window, text="文心一言", command=start_request_baidu,
#                                   activebackground="#0f73ef",
#                                   font="等线 16 bold")
# baidu_btn_button.place(relx=0.65, rely=0.1, relwidth=0.1, relheight=0.05)

sting_clean_button = tkinter.Button(window, text="清空", command="handle_formate_timestamp",
                                    activebackground="#0f73ef",
                                    font="等线 16 bold", bg="#1E1F22", fg="#a9b7c6")
sting_clean_button.bind("<Button-1>", clean_input)
sting_clean_button.place(relx=0.655, rely=0.1, relwidth=0.0375, relheight=0.05)

clp_json = tkinter.Button(window, text="复制",
                          command=copy_to_json_clipboard, activebackground="#0f73ef", font="等线 16 bold", bg="#1E1F22",
                          fg="#a9b7c6")
clp_json.place(relx=0.6925, rely=0.1, relwidth=0.0375, relheight=0.05)

show_upload_speed = tkinter.Label(window, text='', font="等线 14 bold", bg="#1E1F22", fg="#a9b7c6", borderwidth=1,
                                  highlightthickness=1, relief=SOLID, highlightbackground="#a9b7c6")
show_upload_speed.place(relx=0.73, rely=0.1, relwidth=0.06, relheight=0.05)

show_download_speed = tkinter.Label(window, text='', font="等线 14 bold", bg="#1E1F22", fg="#a9b7c6", borderwidth=1,
                                    highlightthickness=1, relief=SOLID, highlightbackground="#a9b7c6")
show_download_speed.place(relx=0.79, rely=0.1, relwidth=0.06, relheight=0.05)

show_cpu_ = tkinter.Label(window, text='', font="等线 14 bold", bg="#1E1F22", fg="#a9b7c6", borderwidth=1,
                          highlightthickness=1, relief=SOLID, highlightbackground="#a9b7c6")
show_cpu_.place(relx=0.85, rely=0.1, relwidth=0.05, relheight=0.05)

show_memory_label = tkinter.Label(window, text='', font="等线 14 bold", bg="#1E1F22", fg="#a9b7c6", borderwidth=1,
                                  highlightthickness=1, relief=SOLID, highlightbackground="#a9b7c6")
show_memory_label.place(relx=0.9, rely=0.1, relwidth=0.05, relheight=0.05)
# 创建一个线程池执行器
executor = ThreadPoolExecutor(max_workers=1)

resource_thread = threading.Thread(target=get_resource_usage, args=(result_queue,))
resource_thread.daemon = True  # Daemonize thread so it will be automatically killed when main program exits
resource_thread.start()
# 在主循环中开始更新过程
handle_memory_cpu()
sting_output_button = tkinter.Text(window, width=40, height=10, border=4, relief=SOLID, font="等线 16 bold",
                                   bg="#1E1F22", fg="#99C794", borderwidth=1, highlightthickness=1,
                                   highlightbackground="#a9b7c6")
sting_output_button.place(relx=0.3, rely=0.15, relwidth=0.65, relheight=0.8)

hand_today_json()

print(f"Successfully start run json tools {datetime.datetime.now()}")

window.mainloop()
